package com.cn.sqlSession;

import com.cn.pojo.Configuration;
import com.cn.pojo.MapperdStatement;
import com.cn.pojo.SqlCommandType;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;

public class MapperProxy<T> implements InvocationHandler, Serializable {

    // session 对象
    private SqlSession sqlSession;

    private Configuration configuration;

    // 代理对象
    private Class<T> mapperInterface;

    public Object newInstance(SqlSession sqlSession, Class<T> mapperInterface, Configuration configuration){
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.configuration = configuration;
        Object proxyInstance = Proxy.newProxyInstance(sqlSession.getClass().getClassLoader(), new Class[] { mapperInterface },
                this);
        return proxyInstance;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        String methodName = method.getName();
        String className = method.getDeclaringClass().getName();
        String statementId = className + "." + methodName;
        MapperdStatement mapperdStatement = configuration.getStatementMap().get(statementId);
        SqlCommandType sqlCommandType = mapperdStatement.getSqlCommandType();

        Object result = new Object();
        switch(sqlCommandType){
            case SELECT:
                System.out.println("SELECT");
                if (method.getGenericReturnType() instanceof ParameterizedType){
                    result = sqlSession.selectList(statementId, args);
                } else {
                    result = sqlSession.selectOne(statementId, args);
                }
                break;
            case INSERT:
                System.out.println("INSERT");
                result = sqlSession.add(statementId, args);
                break;
            case UPDATE:
                System.out.println("UPDATE");
                result = sqlSession.updateById(statementId, args);
                break;
            case DELETE:
                System.out.println("DELETE");
                result = sqlSession.delById(statementId, args);
                break;
            default:
                System.out.println("default");

                break;
        }


        return result;
    }
}
